<template>
  <div>
    <el-form :model="form" :rules="dataRule" ref="dataForm" label-width="100px" size="small">
      <el-tabs v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="基本信息" name="first">
          <el-row type="flex" justify="left">
            <el-col :span="12">
              <el-form-item label="文件名称" prop="servName">
                <el-input v-model="form.servName"></el-input>
              </el-form-item>
              <el-form-item label="服务描述">
                <el-input type="textarea" v-model="form.servDescribe"></el-input>
              </el-form-item>
              <el-form-item label="文件类型">
                <el-select v-model="form.servDataType" placeholder="文件类型">
                  <el-option label="shp" value="51"></el-option>
                  <el-option label="dem" value="52"></el-option>
                  <el-option label="dom" value="53"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="上传文件" prop="servUrl">
                <el-upload
                    class="upload-demo"
                    :headers="form.headers"
                    :action="form.upload_img.uploadUrl"
                    :before-upload="beforeUploadHandle_img"
                    :multiple="false"
                    :limit="1"
                    :on-success="successHandle_img"
                    :on-preview="handlePreview"
                    :file-list="form.upload_img.fileList">
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item label="发布单位">
                <el-input v-model="form.servUnit"></el-input>
              </el-form-item>
              <el-form-item label="联系人">
                <el-input v-model="form.servUser"></el-input>
              </el-form-item>
              <el-form-item label="联系电话">
                <el-input v-model="form.servPhone"></el-input>
              </el-form-item>
              <el-form-item label="联系邮箱">
                <el-input v-model="form.servEmail"></el-input>
              </el-form-item>
              <el-form-item label="联系人地址">
                <el-input v-model="form.servAddress"></el-input>
              </el-form-item>
              <el-form-item label="关键词">
                <el-tag
                    :key="tag"
                    v-for="tag in form.servKeyword"
                    closable
                    :disable-transitions="false"
                    @close="handleClose(tag)">
                  {{ tag }}
                </el-tag>
                <el-input
                    class="input-new-tag"
                    v-if="form.inputVisible"
                    v-model="form.inputValue"
                    ref="saveTagInput"
                    size="small"
                    @keyup.enter.native="handleInputConfirm"
                    @blur="handleInputConfirm">
                </el-input>
                <el-button v-else class="button-new-tag" size="small" @click="showInput">+ 关键词</el-button>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="可见方式" prop="servLimit">
                <el-select v-model="form.servLimit" @change="visibleWayChange" placeholder="可见方式">
                  <el-option label="公开" value="1"></el-option>
                  <el-option label="条件公开" value="2"></el-option>
                  <el-option label="线下" value="3"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="可见范围">
                <el-input v-model="form.roleNameList"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
        <el-tab-pane label="使用帮助" name="second">
          <el-row type="flex" justify="left">
            <el-col :span="12">
              <el-form-item label="上传文档" style="padding-top: 20px">
                <el-upload
                    class="upload-demo"
                    ref="upload_wd"
                    :headers="form.headers"
                    :action="form.upload_wd.uploadUrl"
                    :before-upload="beforeUploadHandle_wd"
                    :multiple="false"
                    :limit="1"
                    :on-success="successHandle_wd"
                    :on-preview="handlePreview"
                    :file-list="form.upload_wd.fileList"
                    :auto-upload="false">
                  <el-button slot="trigger" size="small" type="primary">选取文件</el-button>
                  <el-button style="margin-left: 10px;" size="small" type="success" @click="submitUpload_wd">确认导入
                  </el-button>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>
        </el-tab-pane>
      </el-tabs>
      <el-form-item>
        <el-button type="primary" @click="dataFormSubmit" :disabled="submitStatus">确定</el-button>
        <el-button @click="cancel">取消</el-button>
      </el-form-item>
    </el-form>
    <!-- 弹窗, 新增 / 修改 -->
    <add-or-update v-if="addOrUpdateVisible" ref="addOrUpdate" @setVisibleRange="setVisibleRange"></add-or-update>
  </div>
</template>

<script>
import AddOrUpdate from './ServiceManageAuthorization'
import {roleList} from '@/api/operations-center/role'
import $axios from '@/network'

export default {
  name: "FileManageCreate",
  data() {
    return {
      submitStatus: false,
      activeName: 'first',//tab页
      addOrUpdateVisible: false,
      form: {
        servName: '',//文件名称
        servDescribe: '',//服务描述
        servDataType: '',//文件类型
        servUrl: '',//上传文件
        servUser: '',//联系人
        servPhone: '',//联系电话
        servEmail: '',//联系邮箱
        servAddress: '',//联系人地址
        servKeyword: [],//关键词
        inputVisible: false,//关键词附加
        inputValue: '',//关键词附加
        servLimit: '',//可见方式
        roleIdList: [],//提交角色id
        roleNameList: '',//显示角色名称
        servApi: '',//文档地址
        upload_wd: {
          uploadUrl: process.env.VUE_APP_API_URL + 'data/upload/upload',
          num: 0,
          successNum: 0,
          fileList: []
        },
        upload_img: {
          uploadUrl: process.env.VUE_APP_API_URL + 'data/upload/upload',
          num: 0,
          successNum: 0,
          fileList: []
        },
        headers: {
          source: process.env.VUE_APP_API_SOURCE,
          Authorization: this.$store.state.Authentication.access_token
        }
      },
      dataRule: {
        servUrl: [
          {required: true, message: '上传文件不能为空', trigger: 'blur'}
        ],
        servName: [
          {required: true, message: '文件名称不能为空', trigger: 'blur'}
        ],
        servLimit: [
          {required: true, message: '可见方式不能为空', trigger: 'blur'}
        ]
      }
    }
  },
  components: {
    AddOrUpdate
  },
  methods: {
    dataFormSubmit() {
      let form = this.form;
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          this.$message({
            message: '请检查数据格式是否正确',
            type: 'warning'
          });
          return false;
        }
        //
        this.submitStatus = true;
        //
        $axios({
          url: '/data/fileService/save',
          method: 'POST',
          data: {
            'servName': form.servName,
            'servDescribe': form.servDescribe,
            'servDataType': form.servDataType,
            'servUrl': form.servUrl,
            'servUser': form.servUser,
            'servPhone': form.servPhone,
            'servEmail': form.servEmail,
            'servAddress': form.servAddress,
            'servKeyword': form.servKeyword.join(','),
            'servLimit': form.servLimit,
            'roleIdList': form.roleIdList,
            'servApi': form.servApi
          }
        }).then(data => {
          if (data && data.code === 200) {
            this.$message({
              message: '操作成功',
              type: 'success',
              duration: 1500,
              onClose: () => {
                this.cancel()
              }
            })
          } else {
            this.submitStatus = false;
            this.$message.error(data.msg)
          }
        })
      })
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    /**
     * 取消添加/修改
     */
    cancel() {
      this.$router.go(-1)
    },
    /**
     * 删除关键词
     * @param tag
     */
    handleClose(tag) {
      this.form.servKeyword.splice(this.form.servKeyword.indexOf(tag), 1);
    },
    /**
     * 关键词
     */
    showInput() {
      this.form.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs['saveTagInput'].$refs.input.focus();
      });
    },
    /**
     * 添加关键词
     */
    handleInputConfirm() {
      let inputValue = this.form.inputValue;
      if (inputValue) {
        this.form.servKeyword.push(inputValue);
      }
      this.form.inputVisible = false;
      this.form.inputValue = '';
    },
    // 上传之前
    beforeUploadHandle_img(file) {
      // if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
      //   this.$message.error('只支持jpg、png、gif格式的图片！')
      //   return false
      // }
      // this.form.num++
    },
    // 上传成功
    successHandle_img(response, file, fileList) {
      this.form.upload_img.fileList = fileList
      if (response && response.code === 200) {
        this.form.servUrl = response.data
      } else {
        this.$message.error(response.msg)
      }
    },
    // 上传之前
    beforeUploadHandle_wd(file) {
      // if (file.type !== 'image/jpg' && file.type !== 'image/jpeg' && file.type !== 'image/png' && file.type !== 'image/gif') {
      //   this.$message.error('只支持jpg、png、gif格式的图片！')
      //   return false
      // }
      // this.form.num++
    },
    // 上传成功
    successHandle_wd(response, file, fileList) {
      this.form.upload_wd.fileList = fileList
      if (response && response.code === 200) {
        this.form.servApi = response.data
      } else {
        this.$message.error(response.msg)
      }
    },
    submitUpload_wd() {
      this.$refs.upload_wd.submit();
      this.$message({
        message: '导入成功',
        type: 'success',
        duration: 1500,
        onClose: () => {
          // this.getDataList()
        }
      })
    },
    uploadSize() {
      let size = event.target.files[0].size / 1024 / 1024;
      this.form.servSize = size.toFixed(2) + " MB";
    },
    handlePreview(file) {
      let url = file.response.data
      window.open(url)
    },
    //更改可见方式
    visibleWayChange(value) {
      this.form.roleIdList = []
      let roleNameArray = []
      if (value === '1') {
        roleList('', true).then((res) => {
          res.data.forEach((item, index) => {
            this.form.roleIdList.push(item.id)
            roleNameArray.push(item.roleName)
            this.form.roleNameList = roleNameArray.join(",")
          })
        })
      }
      if (value === '2') {
        this.addOrUpdateVisible = true
        this.$nextTick(() => {
          this.$refs.addOrUpdate.init()
        })
      }
      if (value === '3') {
        this.form.roleNameList = ''
      }
    },
    setVisibleRange(roleNameStr, roleIdList) {
      this.form.roleNameList = roleNameStr
      this.form.roleIdList = roleIdList
    }
  }
}
</script>

<style lang="scss" scoped>
.el-tag + .el-tag {
  margin-left: 10px;
}

.button-new-tag {
  margin-left: 10px;
  height: 32px;
  line-height: 30px;
  padding-top: 0;
  padding-bottom: 0;
}

.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}

img {
  border: 2px solid #8f8e8e
}

.el-form {
  .el-form-item {
    .el-input {
      width: 400px;
    }

    .el-select {
      width: 400px;
    }

    .el-textarea {
      width: 400px;
    }
  }
}
</style>
